import React, { useState } from 'react'
import { Layout, Menu } from 'antd'
import { 
  DashboardOutlined,
  DesktopOutlined,
  TeamOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined
} from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'

const { Sider } = Layout

const Sidebar = () => {
  const { user } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const [collapsed, setCollapsed] = useState(false)

  const menuItems = [
    {
      key: '/dashboard',
      icon: <DashboardOutlined />,
      label: '仪表板',
    },
    {
      key: '/devices',
      icon: <DesktopOutlined />,
      label: '设备管理',
    },
    ...(user?.role === 'super_admin' ? [{
      key: '/admin/users',
      icon: <TeamOutlined />,
      label: '用户管理',
    }] : [])
  ]

  const handleMenuClick = ({ key }) => {
    navigate(key)
  }

  const toggleCollapsed = () => {
    setCollapsed(!collapsed)
  }

  return (
    <Sider 
      trigger={null} 
      collapsible 
      collapsed={collapsed}
      style={{
        background: '#fff',
        boxShadow: '2px 0 8px rgba(0,0,0,0.15)',
      }}
    >
      <div style={{
        padding: '16px',
        textAlign: 'center',
        borderBottom: '1px solid #f0f0f0',
        background: '#001529',
        color: 'white'
      }}>
        {!collapsed && (
          <h3 style={{ color: 'white', margin: 0 }}>Things IoT</h3>
        )}
        {collapsed && (
          <h3 style={{ color: 'white', margin: 0 }}>IoT</h3>
        )}
      </div>
      
      <div style={{
        padding: '8px',
        textAlign: 'center',
        borderBottom: '1px solid #f0f0f0',
        cursor: 'pointer'
      }} onClick={toggleCollapsed}>
        {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
      </div>

      <Menu
        mode="inline"
        selectedKeys={[location.pathname]}
        items={menuItems}
        onClick={handleMenuClick}
        style={{
          borderRight: 0,
          height: 'calc(100vh - 120px)',
          overflow: 'auto'
        }}
      />
    </Sider>
  )
}

export default Sidebar